package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"hc/app"
	"hc/model"
	"math/rand"
)


func main() {

	defer func() {
		app.Shutdown()
	}()

	r := gin.Default()

	goodsId := 1
	number := 1


	r.GET("/orderV1", func(c *gin.Context) {
		// 判断库存
		var goods model.Goods
		if goods.Get(goodsId) {
			return
		}
		if goods.StockOut() {
			return
		}

		// mysql事务
		userId := rand.Intn(1000000)
		var order model.Order
		success := order.OrderVersion1(userId, goodsId, number)

		c.JSON(200, gin.H{
			"result": success,
		})
	})

	r.GET("/orderV2", func(c *gin.Context) {
		// redis实时减库存+mysql+mq异步减库存
		userId := rand.Intn(1000000)
		var order model.Order
		success := order.OrderVersion2(userId, goodsId, number)

		c.JSON(200, gin.H{
			"result": success,
		})
	})

	r.GET("/orderV3", func(c *gin.Context) {
		// redis实时减库存+mysql分表+mq异步减库存
		userId := rand.Intn(1000000)
		var order model.Order
		success := order.OrderVersion3(userId, goodsId, number)

		c.JSON(200, gin.H{
			"result": success,
		})
	})

	r.GET("/orderV4", func(c *gin.Context) {
		// redis实时减库存+mysql分库分表+mq异步减库存
		userId := rand.Intn(1000000)
		var order model.Order
		success := order.OrderVersion4(userId, goodsId, number)

		c.JSON(200, gin.H{
			"result": success,
		})
	})

	r.GET("/orderV5", func(c *gin.Context) {
		// redis实时减库存+mysql分库分表+mq多主机异步减库存
		userId := rand.Intn(1000000)
		var order model.Order
		success := order.OrderVersion5(userId, goodsId, number)

		c.JSON(200, gin.H{
			"result": success,
		})
	})

	r.GET("/orderV6", func(c *gin.Context) {
		// redis实时减库存+mysql分库分表+mq多主机异步减库存+内存售完标记
		userId := rand.Intn(1000000)
		var order model.Order
		success := order.OrderVersion6(userId, goodsId, number)

		c.JSON(200, gin.H{
			"result": success,
		})
	})

	r.GET("/orderV7", func(c *gin.Context) {
		// redis实时减库存+mysql二叉树分库分表+mq多主机异步减库存+内存售完标记
		userId := rand.Intn(1000000)
		var order model.Order
		success := order.OrderVersion7(userId, goodsId, number)

		c.JSON(200, gin.H{
			"result": success,
		})
	})

	// 查看内存标记
	r.GET("/stockOut", func(c *gin.Context) {
		value, ok := model.GetStockOut(goodsId)

		userId := rand.Intn(100)
		fmt.Println("userId = ",  userId, "db = ", userId % 4 + 1, "table = ", userId / 10 % 16 +1)
		// 分表
		//tableIndex := userId / 10  % orderTableCount + 1

		c.JSON(200, gin.H{
			"value": value,
			"ok": ok,
		})
	})


	r.Run()
}